package studyguide.ch16;

import java.io.IOException;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

public class RMSServerMidlet extends MIDlet {

	private final Command exitCommand;
	private final Display display;
	
	private final Form mainForm;
	private final ChoiceGroup records;
	
	private RecordStore recordStore;
	
	private class SampleCommandListener implements CommandListener {
		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
	}
	
	public RMSServerMidlet() throws IOException {
		mainForm = new Form("Server RMS Sample");
		exitCommand = new Command("Exit", Command.EXIT, 1);
		
		mainForm.addCommand(exitCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		mainForm.setCommandListener(listener);
		display = Display.getDisplay(this);
		
		records = new ChoiceGroup("Records:", Choice.MULTIPLE);
		
		mainForm.append(records);
	}
	
	protected void destroyApp(boolean unconditional) {
		closeDatabase();
	}

	protected void pauseApp() {
		closeDatabase();
	}

	protected void startApp() throws MIDletStateChangeException {
		try {
			display.setCurrent(mainForm);
			openDatabase();
			
			// Update presentation with database status
			records.deleteAll();
			RecordEnumeration enRecs = recordStore.enumerateRecords(null, null, false);
			while (enRecs.hasNextElement()) {
				byte[] serializedData = enRecs.nextRecord();
				String record = new String(serializedData);
				records.append(record, null);
			}
			enRecs.destroy();
			
		} catch (RecordStoreNotOpenException e) {
			throw new MIDletStateChangeException(e.getMessage());
		} catch (InvalidRecordIDException e) {
			throw new MIDletStateChangeException(e.getMessage());
		} catch (RecordStoreException e) {
			throw new MIDletStateChangeException(e.getMessage());
		}
	}

	private void openDatabase() {
		try {
			recordStore = RecordStore.openRecordStore("MyOtherRecordStore", false);
			System.out.println("Database already existed and contained " 
					+ recordStore.getNumRecords() + " records");
		} catch (RecordStoreNotFoundException e) {
			try {
				// If the database did not exist, create and populate it with sample data
				System.out.println("Creating and populating database");
				recordStore = RecordStore.openRecordStore(
						"MyOtherRecordStore", 
						true,
						RecordStore.AUTHMODE_ANY,
						false);
				
				byte [] record = "Record A".getBytes();
				recordStore.addRecord(record, 0, record.length);
				record = "Record B".getBytes();
				recordStore.addRecord(record, 0, record.length);
				record = "Record C".getBytes();
				recordStore.addRecord(record, 0, record.length);
			} catch (RecordStoreException e1) {
				throw new RuntimeException(e.getMessage());
			}
		} catch (RecordStoreFullException e) {
			throw new RuntimeException(e.getMessage());
		} catch (RecordStoreException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	private void closeDatabase() {
		try {
			recordStore.closeRecordStore();
		} catch (RecordStoreNotOpenException e) {
			throw new RuntimeException(e.getMessage());
		} catch (RecordStoreException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

}
